package com.solution.util.scheduler.job;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.solution.constant.LoginConstants;
import com.solution.constant.SystemVariableConstants;
import com.solution.delegate.SystemVariableServiceDelegate;
import com.solution.delegate.UserInfoServiceDelegate;
import com.solution.exception.DelegateException;
import com.solution.exception.ServiceBeanException;
import com.solution.model.SystemVariable;
import com.solution.model.UserInfo;
import com.solution.util.SearchVO;

public class ExamineeExpiryJob implements Job{
	private Logger logger = Logger.getLogger(ExamineeExpiryJob.class.getName());

	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		try {
			UserInfoServiceDelegate userInfoServiceDelegate = new UserInfoServiceDelegate();
			SearchVO searchVO = new SearchVO();
			searchVO.addIsNotNullCondition("examTypeId");
			searchVO.addEqualsCondition("status", new Short(LoginConstants.USER_ACTIVE));
			List<UserInfo> activeExaminees = userInfoServiceDelegate.searchUser(searchVO);
			
			SystemVariableServiceDelegate systemVariableService = new SystemVariableServiceDelegate();
			
			for(UserInfo examinee : activeExaminees){
				SystemVariable systemVariable = systemVariableService.getValue(SystemVariableConstants.EXAMINEE_EXPIRY_DAYS, examinee.getClientType().getId());
				if(!checkPasswordAge(examinee, new Long(systemVariable.getVariableValue().trim()))){
					 updateExemineeStatus(examinee);
				}
			}
		}
		catch (DelegateException e){
			logger.error(e);
		}
		catch (ServiceBeanException e){
			logger.error(e);
		}
	}

	private boolean checkPasswordAge(UserInfo userInfo, long noOfDays){
		Calendar calPrevious = Calendar.getInstance();
		Calendar calToday = Calendar.getInstance();
		calPrevious.setTime(userInfo.getCreatedOn());
		calToday.setTime(new Date());
		long diff = (calToday.getTimeInMillis() - calPrevious.getTimeInMillis())/(1000 * 60 * 60 * 24);
		if(diff > noOfDays){
			return false;
		}else{
			return true;
		}
	}
		
	private void updateExemineeStatus(UserInfo userInfo) throws ServiceBeanException, DelegateException{
		UserInfoServiceDelegate userInfoService = new UserInfoServiceDelegate();
		userInfo.setStatus(LoginConstants.USER_LOGIN_EXPIRED);
		userInfoService.update(userInfo);
	}
}
